<?php

class Variables_IndexController extends Zend_Controller_Action {
	private $nav;
	
     public function init() {
		$this->nav = new App_Util_Navegacion();
		
		 if (App_User::getCodigoPadreRol()== Roles_Model_Roles::CODPADRE_ADMIN){
		    $this->nav->agregar_navegacion ( "Listado de variables", "/variables/index", "Listado de varibles" );
		 }else{
		    $this->nav->agregar_navegacion ( "Listado de variables", "/variables/index/misvariables", "Listado de varibles" );
		 }
	}
	
    public function indexAction() {
        $this->view->nav = $this->nav;
        $Variables = new Variables_Model_Variables();
		
        $datos = array();
        if (App_User::getCodigoPadreRol()!= Roles_Model_Roles::CODPADRE_ADMIN){
            $datos["codusuario"] = App_User::getCodigoUsuario();
        }
        
        $this->view->datos = $Variables->getVariables($datos);
    }

    public function crearvariableAction() {
        $Variables = new Variables_Model_Variables();
        
        $datos = array();
        $form1 = new Variables_Form_Crearvariable();
        
        $accion = "Crear ";
        $codvariable = $this->_getParam("codvariable");
        if (!empty($codvariable)){
            $datos= $Variables->getVariable($codvariable);
            
    		$form1->populate($datos);
            $form1->tiponaturaleza->setAttrib('disabled', 'disabled');
            $form1->tipocuantitativa->setAttrib('disabled', 'disabled');
            $form1->tipogrado->setAttrib('disabled', 'disabled');
            $accion = "Modificar ";
            
            $this->view->variable = $datos;
            $this->view->datosdimensiones = $Variables->getDimensionesVariable(array("codvariable"=>$codvariable));
        }

        $this->view->verform2 = false;
        $form2 = new Variables_Form_Dimensioncuan();
        $coddimension = $this->_getParam("coddimension");
        if (!empty($coddimension)){
            $datos= $Variables->getDimensionVariable($coddimension);
    		$form2->populate($datos);
    		$this->view->verform2 = true;
        }
        
        $this->nav->agregar_navegacion("{$accion} Variable", "","{$accion} Variable");
		$this->view->nav = $this->nav;

        $form1->setAction($this->view->baseUrl("/variables/index/guardarvariable"));
        $form1->recoverFromRedirect();
		$this->view->formvariable = $form1;

		$form2->setAction($this->view->baseUrl("/variables/index/guardardimension"));
        $form2->recoverFromRedirect();
		$this->view->formdimension = $form2;

    }
    
	
    public function guardarvariableAction(){
        $form = new Variables_Form_Crearvariable();
        if($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())){
			try {
				$Variables = new Variables_Model_Variables();
				$datos = $this->getRequest()->getPost();
				if (empty($datos["codvariable"])){
				    $datos["codusuariocrea"] = App_User::getCodigoUsuario();
				}
				$key = $Variables->guardarVariable($datos);
				if (empty($datos["codvariable"])){
				    $datos["codvariable"] = $key;
				    
    				if ($datos["tipogrado"]==1){
    				    $datosd["codvariable"]     = $datos["codvariable"];
    				    $datosd["nombredimension"] = $datos["nombrevariable"];
    				    $datosd["codunidad"]       = 4;
    				    $parametros["coddimension"] = $Variables->guardarDimensionVariable($datosd);
    				}
				}
				
				$this->view->priorityMessenger("Los datos se han guardado correctamente", "success");
			} catch (Exception $e) {
				$this->view->priorityMessenger($e->getMessage(), "error");
			}
        } else {
            $form->setStateRedirect();
        }
        $cadena = "";
        
        if (!empty($datos["codvariable"])){
            $parametros["codvariable"] = $datos["codvariable"];
            $cadena =App_Util_SafeUrl::encriptar($parametros, false);
            $this->_helper->redirector( "crearvariable","index","variables",$cadena);
        }
         $this->_helper->redirector( "crearvariable","index","variables");
	}
	
   public function eliminarvariableAction() {
        try {
            $Variables = new Variables_Model_Variables();
            $Variables->eliminarVariable($this->_getParam("codvariable"));
            $this->view->priorityMessenger("El registro se eliminó correctamente", "success");
        } catch(Exception $e) {
            $this->view->priorityMessenger($e->getMessage(), "error");
        }
        $this->_helper->redirector("index");
    }
		
    public function creardimensionAction() {
    	$Variables = new Variables_Model_Variables();

        $codvariable             = $this->_getParam("codvariable");
        $coddimension 			 = $this->_getParam("coddimension");
    	
        $this->view->variable   = $Variables->getVariable($codvariable);
        $datos = array();
        $accion = "Crear dimensi&oacute;n";
        $form = new Variables_Form_Dimensioncuan();
        
        $form-> removeElement("valornum");
        $form-> removeElement("fechaactualiza");
        $form-> removeElement("comentario");
        $form-> removeElement("codrango");
                
        if (!empty($coddimension)){
        	$this->view->dimension 	= $Variables->getDimensionesVariable(array("coddimension"=>$coddimension));
        	$datos = $this->view->dimension[0];
    		$form->populate($datos);
    		if ($this->view->variable["tiponaturaleza"]==1){
    		    $form->nombredimension->setAttrib('readonly', 'readonly');
    		}
    		$accion = "Modificar dimensi&oacute;n";
        }else{
			$datos["codvariable"] = $codvariable;
			$form->populate($datos);
        }

        $parametros["codvariable"] = $codvariable;
        $cadena =App_Util_SafeUrl::encriptar($parametros, true);
                
    	$this->nav->agregar_navegacion("Modificar Variable", "/variables/index/crearvariable/{$cadena}","Modificar Variable");
    	$this->nav->agregar_navegacion ( $accion, "", "" );
        $this->view->nav = $this->nav;
        
        $form->setAction($this->view->baseUrl("/variables/index/guardardimension"));
        $form->recoverFromRedirect();
		$this->view->form= $form;

    }
    
    public function guardardimensionAction(){
        $form = new Variables_Form_Dimensioncuan();
        $form-> removeElement("valornum");
        $form-> removeElement("codrango");
        $form-> removeElement("fechaactualiza");
        $form-> removeElement("comentario");
        
        if($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())){
			try {
				$Variables = new Variables_Model_Variables();
				$datos = $this->getRequest()->getPost();
				$key = $Variables->guardarDimensionVariable($datos);
				$this->view->priorityMessenger("Los datos se han guardado correctamente", "success");
			} catch (Exception $e) {
				$this->view->priorityMessenger($e->getMessage(), "error");
			}
        } else {
            $form->setStateRedirect();
        }
        
        if (!empty($datos["coddimension"])){
            $parametros["coddimension"] = $datos["coddimension"];
        }
                
        $cadena = "";
        $parametros["codvariable"] = $datos["codvariable"];
        $cadena =App_Util_SafeUrl::encriptar($parametros, false);
        $this->_helper->redirector( "creardimension","index","variables",$cadena);
	}
    
     public function usuariosdimensionAction() {
        $Variables = new Variables_Model_Variables();
        
        $codvariable             = $this->_getParam("codvariable");
        $coddimension 			 = $this->_getParam("coddimension");
        
        $this->view->variable   = $Variables->getVariable($codvariable);
        $this->view->dimension 	= $Variables->getDimensionesVariable(array("coddimension"=>$coddimension));
        
        
        $parametros["codvariable"] = $codvariable;
        $cadena =App_Util_SafeUrl::encriptar($parametros, true);
                
    	$this->nav->agregar_navegacion("Modificar Variable", "/variables/index/crearvariable/{$cadena}","Modificar Variable");
        $this->nav->agregar_navegacion("Asignar usuarios", "","Asignar usuarios");
		$this->view->nav = $this->nav;
		
		$datos["coddimension"] = $coddimension;
		$datos["codvariable"] = $codvariable;
        $form = new Variables_Form_AsignarUsuario();
		$form->populate($datos);
        $form->setAction($this->view->baseUrl("/variables/index/guardarasignacion"));
        $form->recoverFromRedirect();
		$this->view->form = $form;
		
		$usuarios = new Usuarios_Model_Usuarios();
		$this->view->datos = $usuarios->getUsuarios("DIMENSIONES",array("coddimension"=>$coddimension));
		
    }

	public function autolistaAction(){
		$this->_helper->layout->disableLayout ();
	    $campoConsulta = strtolower($this->_getParam ( 'term' ));
	    $datos["coddimension"] = $this->_getParam("coddimension");
		$items=array();
		if ($campoConsulta){
			$usuarios = new Usuarios_Model_Usuarios();
			$items= $usuarios->cargardatosauto("DIMENSIONES",$campoConsulta,$datos);
		}
		$this->view->items=$items;
	}
       
    public function guardarasignacionAction(){
        $form = new Variables_Form_AsignarUsuario();
        if($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())){
			try {
				$usuarios = new Usuarios_Model_Usuarios ();
				$datos = $this->getRequest()->getPost();
				unset($datos["usuario"]);
				unset($datos["btnSubmit"]);
				unset($datos["codvariable"]);
				$usuarios->asignarUsuarioDIMENSION($datos);
				$this->view->priorityMessenger("Los datos se han guardado correctamente", "success");
			} catch (Exception $e) {
				$this->view->priorityMessenger($e->getMessage(), "error");
			}
        } else {
            $form->setStateRedirect();
        }
        $parametros["codvariable"] = $this->getRequest ()->getPost ("codvariable");
        $parametros["coddimension"] = $datos["coddimension"];
        $this->_helper->redirector( "usuariosdimension","index","variables",App_Util_SafeUrl::encriptar($parametros, false));
	}
    
	public function desasignarusuarioAction(){
	    $coddimension = $this->getRequest ()->getPost ( 'coddimension' );
        $seleccionados = $this->_getParam("seleccionados", array());
        
        $parametros["codvariable"] = $this->getRequest ()->getPost ("codvariable");
        $parametros["coddimension"] = $coddimension;

        if(count($seleccionados)==0) {
			$this->view->priorityMessenger("Debe seleccionar por lo menos un registro", "warning");
			$this->_helper->redirector( "usuariosdimension","index","variables",App_Util_SafeUrl::encriptar($parametros, false));
		}
		try {
		    $usuarios = new Usuarios_Model_Usuarios ();
			$usuarios->desasignarUsuarioDIMENSION($coddimension, $seleccionados);
			$this->view->priorityMessenger("Los datos se han guardado correctamente", "success");
		} catch (Exception $e) {
			$this->view->priorityMessenger($e->getMessage(), "error");
		}
        $this->_helper->redirector( "usuariosdimension","index","variables",App_Util_SafeUrl::encriptar($parametros, false));
	}
	
    
    
    public function historicodimensionAction() {
    	$Variables = new Variables_Model_Variables();

        $codvariable             = $this->_getParam("codvariable");
        $coddimension 			 = $this->_getParam("coddimension");
    	
        $parametros["codvariable"] = $codvariable;
        $cadena =App_Util_SafeUrl::encriptar($parametros, true);
                
        if (App_User::getCodigoPadreRol()== Roles_Model_Roles::CODPADRE_ADMIN){
            $this->nav->agregar_navegacion("Modificar Variable", "/variables/index/crearvariable/{$cadena}","Modificar Variable");
        }
                
    	
    	$this->nav->agregar_navegacion ( "Listado histórico", "", "Listado histórico Variable / Dimensión" );
        $this->view->nav = $this->nav;
        
        
        $this->view->variable   = $Variables->getVariable($codvariable);
        $this->view->dimension 	= $Variables->getDimensionesVariable(array("coddimension"=>$coddimension));
        
        $this->view->datos = $Variables->getHistoricoDimension(array("coddimension"=>$coddimension));
    }
		
    public function misvariablesAction() {
        $this->view->nav = $this->nav;
        $Variables = new Variables_Model_Variables();
        $datos["codusuario"] = App_User::getCodigoUsuario();
        
        $this->view->datos = $Variables->getVariables($datos);
    }
    
    public function actualizardimensionAction() {
    	$Variables = new Variables_Model_Variables();

        $codvariable             = $this->_getParam("codvariable");
        $coddimension 			 = $this->_getParam("coddimension");
    	
        $this->view->variable   = $Variables->getVariable($codvariable);
        $this->view->dimension 	= $Variables->getDimensionesVariable(array("coddimension"=>$coddimension));
        
        $datos = array();
        $form = new Variables_Form_Dimensioncuan();
        $form-> removeElement("tipoinstrumento");
        $form-> removeElement("codconexionbd");
        $form-> removeElement("sql");
        
        if ($this->view->variable["tiponaturaleza"]==1){
            $form-> removeElement("codrango");
        }else{
            $form-> removeElement("valornum");
            $array_rangos = $Variables->getRangos(array("codescala"=>$this->view->dimension[0]["codescala"]));
            $form->codrango->setMultiOptions($array_rangos);
        }
        
        $datos = $this->view->dimension[0];
        $datos["valornum"] = "";
        $datos["valortexto"] = "";
        $datos["fechaactualiza"] = new Zend_Date();
        $datos["codigoescala"] = $this->view->dimension[0]["codescala"];
    	
		$form->populate($datos);
	    $form->nombredimension->setAttrib('disabled', 'disabled');
	    $form->codunidad->setAttrib('disabled', 'disabled');
	    $form->codescala->setAttrib('disabled', 'disabled');
	    
	    

        $parametros["codvariable"] = $codvariable;
        $cadena =App_Util_SafeUrl::encriptar($parametros, true);
                
    	$this->nav->agregar_navegacion ( "Actualizar dimensi&oacute;n", "", "" );
        $this->view->nav = $this->nav;
        
        $form->setAction($this->view->baseUrl("/variables/index/guardaractualizardimension"));
        $form->recoverFromRedirect();
		$this->view->form= $form;

    }
    
    public function guardaractualizardimensionAction(){
        $form = new Variables_Form_Dimensioncuan();
        $form-> removeElement("nombredimension");
        $form-> removeElement("codunidad");
        $form-> removeElement("tipoinstrumento");
        $form-> removeElement("codconexionbd");
        $form-> removeElement("sql");
        
        $codvariable             = $this->_getParam("codvariable");
        $Variables = new Variables_Model_Variables();
        $this->view->variable   = $Variables->getVariable($codvariable);
        
        if ($this->view->variable["tiponaturaleza"]==1){
            $form-> removeElement("codrango");
        }else{
            $form-> removeElement("valornum");
        }
        
        
        if($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())){
            $fechaactualiza = $form->getValue("fechaactualiza");
            if(empty($fechaactualiza)) {
			    $form->getElement("fechaactualiza")->addError("La fecha de actualización es requerida");
				$form->setStateRedirect();
			} else {
    			try {
    				$datos = $this->getRequest()->getPost();
    				
                    if ($this->view->variable["tiponaturaleza"]==2){
                        $array_rangos = $Variables->getRangos(array("codescala"=>$datos["codigoescala"]));
                        $datos["valortexto"] =  $array_rangos[$datos["codrango"]];
                    }
            				
    				$key = $Variables->guardarDimensionVariable($datos);
    				$datos["codusuario"] = App_User::getCodigoUsuario();
    				$key = $Variables->guardarHistoricoDimension($datos);
    				$this->view->priorityMessenger("Los datos se han guardado correctamente", "success");
    				
    			} catch (Exception $e) {
    				$this->view->priorityMessenger($e->getMessage(), "error");
    			}
			}
        } else {
            $form->setStateRedirect();
        }
        
        $cadena = "";
        $parametros["codvariable"] = $datos["codvariable"];
        $parametros["coddimension"] = $datos["coddimension"];
        $cadena =App_Util_SafeUrl::encriptar($parametros, false);
        $this->_helper->redirector( "actualizardimension","index","variables",$cadena);
	}
	
    public function selecvariablesAction() {
        $this->_helper->layout->disableLayout ();
        $Variables = new Variables_Model_Variables();
        $datos["seleccion"] = "expresion";
        $this->view->datos = $Variables->getVariables($datos);
    }
    	
}